package com.lagou.task03;

import java.io.*;
import java.util.concurrent.Callable;

public class FileEditor implements Callable {

    private File oldFile;
    private File newFile;

    public FileEditor() {
    }

    public FileEditor(File oldFile, File newFile) {
        this.oldFile = oldFile;
        this.newFile = newFile;
    }

    public File getOldFile() {
        return oldFile;
    }

    public void setOldFile(File oldFile) {
        this.oldFile = oldFile;
    }

    public File getNewFile() {
        return newFile;
    }

    public void setNewFile(File newFile) {
        this.newFile = newFile;
    }

    @Override
    public Object call() throws Exception {
        copyAllFile(oldFile,"");
        return new Object();
    }

    public void copyAllFile(File file, String subDir){
        File[] files = file.listFiles();
        for (File tf : files) {
            // 需要复制的目录或文件的绝对路径，加上目录自己的名字
            String targetUrl = getNewFile().getAbsolutePath() + subDir + "/" + tf.getName();

            if (tf.isDirectory()){ // 需要复制的 file 对象
                File newDirectory = new File(targetUrl);

                System.out.println("正在拷贝目录：" + tf.getAbsolutePath());
                System.out.println(newDirectory.mkdir() ? "目录复制成功" : "目录复制失败");
                System.out.println("新的目录路径：" + targetUrl);
                System.out.println();
                // 拼接子目录路径 继续递归复制
                copyAllFile(tf,subDir + "/" + tf.getName());

            }else if (tf.isFile()){
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;

                try {
                    // 1.创建 BufferInputStream 和旧文件关联
                    bis = new BufferedInputStream(new FileInputStream(tf.getAbsoluteFile()));

                    // 2.创建 BufferOutputStream 和新文件关联
                    bos = new BufferedOutputStream(new FileOutputStream(targetUrl));

                    System.out.println("正在拷贝的旧文件路径：" + tf.getAbsolutePath());

                    byte[] bArr = new byte[1024];
                    int res = 0;
                    while ((res = bis.read()) != -1){
                        bos.write(bArr,0,res);
                    }
                    System.out.println("拷贝完成，新文件路径：" + targetUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != bos) {
                        try {
                            bos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != bis) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            System.out.println();
        }
    }
}
